package com.zkld.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zkld.mapper.UserMapper;
import com.zkld.pojo.User;
import com.zkld.pojo.UserExample;
import com.zkld.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void addUser(User user) {
        String password = DigestUtils.md5Hex(user.getPassword());
        user.setPassword(password);
        userMapper.insert(user);
    }

    @Override
    public void delete(User user) {
        userMapper.deleteByPrimaryKey(user.getId());
    }

    @Override
    public String  update(User user,String oldPassword) {
        User user1 = userMapper.selectByPrimaryKey(user.getId());
        oldPassword = DigestUtils.md5Hex(oldPassword);
        if (oldPassword.equals(user1.getPassword())){
            userMapper.updateByPrimaryKey(user);
            return "";
        }else {
            return "原密码输入有误";
        }

    }

    @Override
    public User query(User user) {
        return userMapper.selectByPrimaryKey(user.getId());
    }

    @Override
    public List<User> queryAll() {
        return userMapper.selectByExample(null);
    }

    @Override
    public PageInfo<User> queryAllByPage(Integer p) {
        PageHelper.startPage(p,12);
        List<User> list = userMapper.selectByExample(null);
        return new PageInfo<>(list);
    }

    @Override
    public User queryByMobile(String mobile) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andMobileEqualTo(mobile);
        List<User> list = userMapper.selectByExample(userExample);
        if (!CollectionUtils.isEmpty(list)){
            return list.get(0);
        }
        return null;
    }

    @Override
    public User queryById(String id) {
        return userMapper.selectByPrimaryKey(Integer.valueOf(id));
    }

}
